package cn.hyatt.common.utils;

import cn.hyatt.common.exception.BusinessException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

import java.util.Set;

/**
 * 验证工具
 *
 * @author hyatt
 */
public class ValidationUtil {
    // 验证者
    static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 验证
     * @param object 验证对象
     * @param <T> 验证对象时泛型
     */
    public static <T> void validate(T object) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if (!violations.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            // 处理验证错误
            for (ConstraintViolation<T> violation : violations) {
                builder.append(violation.getPropertyPath()).append(":")
                        .append(violation.getMessage()).append(";");
            }
            throw new BusinessException(builder.toString());
        }
    }

}
